//
//  QCHomeViewController.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/1/16.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit

private let homeCellID = "homeCellID"

class QCHomeViewController: QCVisitorViewController {
    
    //创建homeViewMidel 对象
    lazy var homeViewModel: QCHomeViewModel = QCHomeViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin {
            visitorView?.setupVisiorViewInfo(imgName: nil, title: nil)
            return
        }
        setUpUI()
        loadData()
    }

   private func setUpUI(){
    
    navigationController!.view.insertSubview(pullDownTipLabel, belowSubview: navigationController!.navigationBar)
        setUpNav()
        setupTableViewInfo()
    }
    private func setUpNav(){
     
        navigationItem.leftBarButtonItem =  UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: #selector(leftClick))
        // 右侧
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(rightClick))
        
    }
    
    //MARK: -设置tableView 相关信息
    private func setupTableViewInfo(){
        // 设置数据源代理
        tableView.dataSource = self
        tableView.delegate = self
        // 注册cell
        tableView.register(QCHomeCell.self, forCellReuseIdentifier: homeCellID)
        // 设置行高 -> 设置自动计算行高UITableViewAutomaticDimension
        tableView.rowHeight = UITableViewAutomaticDimension
        // 设置预估行高(预估行高越接近于真实高度越好)
        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = .none
        tableView.tableFooterView = footView
        //将刷新控件添加到tableView上
        tableView.addSubview(refreshControl)
        //添加监听事件
        refreshControl.addTarget(self, action: #selector(refreshAction), for: UIControlEvents.valueChanged)
    }
    
    //MARK: - 懒加载控件
    // 风火轮
    fileprivate lazy var footView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        // 设置颜色
        view.color = KCOlOR
        return view
    }()
    
    //刷新控件
    fileprivate lazy var refreshControl:QCRefreshControl = QCRefreshControl()
    
    //下拉label
    fileprivate lazy var pullDownTipLabel:UILabel = {
       let lab = UILabel(fontSize: QCNORMALFONTSIZE, textColor: UIColor.white)
        lab.frame = CGRect(x: 0, y: 64-35, width: UIScreen.main.bounds.width, height: 35)
        lab.textAlignment = .center
        lab.backgroundColor = KCOlOR
        lab.isHidden = true
        return lab
    }()
}

extension QCHomeViewController:UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: homeCellID, for: indexPath) as! QCHomeCell
        
        cell.statusViewModel = homeViewModel.dataArray[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == homeViewModel.dataArray.count - 1 && !footView.isAnimating {
            footView.startAnimating()
            loadData()
        }
    }
    
    
    
}

extension QCHomeViewController {
    func loadData(){
        
        homeViewModel.getHomeData(isPullUP:footView.isAnimating) {(isFinish,count) in
           //风火轮没动画是下拉刷新  动画时 上拉加载更多
            if !self.footView.isAnimating {
               
          self.setupPullDownTipLabelAnim(count: count)
                
            }
            
            self.endRefreshing()
            
            if !isFinish {
                print("请求失败")
            }else {
                
          self.tableView.reloadData()

            }
        }
    }
    // 设置下拉刷新指示label的动画&&给lable设置text  -> 监测为下拉刷新的时候才会执行动画
    func setupPullDownTipLabelAnim(count: Int){
        if !self.pullDownTipLabel.isHidden {
            return
        }
        var text = ""
        
        if count <= 0 {
            text = "您已经是最新的微博啦"
        }else {
            text = "您更新到\(count)条新微博"
        }
        
        self.pullDownTipLabel.text = text
        
        self.pullDownTipLabel.isHidden = false
        
        //设置动画
        UIView.animate(withDuration: 1, animations: {
            
            self.pullDownTipLabel.transform = CGAffineTransform(translationX: 0, y: 35)
            
        }) { (_) in
        
            UIView.animate(withDuration: 1, delay: 2, options: [], animations: {
                self.pullDownTipLabel.transform = CGAffineTransform.identity
            }, completion: { (_) in
                self.pullDownTipLabel.isHidden = true
            })
            
        }
        
    }
    
    func endRefreshing(){
        self.refreshControl.endRefreshing()
        self.footView.stopAnimating()
    }
}
extension QCHomeViewController {
    
    // 左侧按钮点击
    @objc fileprivate func leftClick(){
        print("左侧按钮点击")
    }
    // 右侧按钮点击
    @objc fileprivate func rightClick(){
        print("右侧按钮点击")
        let tempVc = QCTempViewController()
        navigationController?.pushViewController(tempVc, animated: true)
    }
    //监听首页下拉刷新事件
    @objc fileprivate func refreshAction(){
        
        //请求数据
        loadData()
//        print("请求数据")
    }
    
}
